package com.lxw.mq.service;


import com.lxw.framework.domain.cms.CmsPage;
import com.lxw.framework.exception.CustomException;
import com.lxw.framework.model.response.CommonCode;
import com.lxw.mq.dao.CmsPageDao;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Optional;

@Service
public class CmsPageServiceImpl implements ICmsPageService {


    @Autowired
    CmsPageDao cmsPageDao;
    @Autowired
    GridFSBucket gridFSBucket;
    @Autowired
    GridFsTemplate gridFsTemplate;


    @Override
    public void wirteFile(String pageId) {
        //读取文件
        Optional<CmsPage> byId = cmsPageDao.findById(pageId);
        if (!byId.isPresent()){
            throw new CustomException(CommonCode.FAIL);
        }
        CmsPage cmsPage = byId.get();
        String htmlFileId = cmsPage.getHtmlFileId();

        //从girdFs中取数据
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(htmlFileId)));
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //合并文件
        GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
        InputStream inputStream = null;
        try {
            inputStream = gridFsResource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取到文件的地址 服务器站点+页面物理路径 + 页面路径+页面名称
        String pagePhysicalPath = cmsPage.getPagePhysicalPath();
        String pageWebPath = cmsPage.getPageWebPath();
        String pageName = cmsPage.getPageName();
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(pagePhysicalPath + pageWebPath + pageName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            //写入到磁盘
            int i = IOUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
